import babel from "rollup-plugin-babel"; //代码转换：es6->es5
import commonjs from "rollup-plugin-commonjs"; //支持commonjs导入导出
import { uglify } from "rollup-plugin-uglify"; //代码压缩
import json from "rollup-plugin-json"; //支持json文件
import npm from "rollup-plugin-node-resolve"; //支持第三方库的导入，如：lodash
import html from "@rollup/plugin-html";
import htmlFile from 'rollup-plugin-html';
import postcss from "rollup-plugin-postcss";
import serve from 'rollup-plugin-serve';
import livereload from "rollup-plugin-livereload";
import copy from 'rollup-plugin-copy'//处理静态资源
import fs from 'fs';

const entryHtml = fs.readFileSync('./index.html', { encoding: 'utf-8' });

const isProduction = process.env.NODE_ENV === "production";

const plugins = [
	commonjs(),
	babel({
		exclude: "node_modules/**",
	}),
	json(),
	npm(),
	htmlFile(),
	postcss(
		{
			extract: 'style.css'
		}
	),
	copy({
		targets: [
			{
				src: './src/assets/img/*',
				dest: 'dist/image'
			}
		]
	}),
	html({
		include: ".",
		template: ({ attributes, bundle, files, publicPath, title }) => {
			return entryHtml
				.replace(
					'<!-- style placeholder -->',
					'<link rel="stylesheet" type="text/css" href="style.css" />',
				)
				.replace(
					'<!-- script placeholder -->',
					`<script type="text/javascript" src="bundle.js"></script>`,
				);
		}
	}),
]
if (isProduction) {
	plugins.push(uglify())
} else {
	const devPlugin = [
		serve({
			open: true,
			// openPage: '/different/page',//浏览器地址栏路径
			port: 3000,
			contentBase: ['dist'],//提供文件的文件夹
		}),
		livereload()
	]
	plugins.push(...devPlugin)
}
export default {
	// input: ["./src/index.js",'./index.html'],//可让html文件也热更新
	input: "./src/index.js",
	output: {
		file: 'dist/bundle.js',
		// dir: "dist",//当存在多个入口时，必须指定dir
		format: "cjs", // 输出格式，支持 'amd', 'cjs', 'es', 'iife' 或 'umd'
	},
	sourceMap: "inline",
	plugins
};
